<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<link rel='stylesheet' type='text/css' href='../fullcalendar/fullcalendar.css' />
<!--<link rel='stylesheet' type='text/css' href='startTheme/css/start/jquery-ui-1.8.11.custom.css
' />-->
<link rel='stylesheet' type='text/css' href='darkHive/css/dark-hive/jquery-ui-1.8.11.custom.css

' />
<link rel='stylesheet' type='text/css' href='../fullcalendar/fullcalendar.print.css' media='print' />
<script type='text/javascript' src='../jquery/jquery-1.5.min.js'></script>
<script type='text/javascript' src='../jquery/jquery-ui-1.8.9.custom.min.js'></script>
<script type='text/javascript' src='../fullcalendar/fullcalendar.min.js'></script>


<script type='text/javascript'>
//database interaction=================================================================
	var db = null;
	 
	try {
		if (window.openDatabase) {
			db = openDatabase("SlotData", "1.0", "HTML5 Database - Slot Reservations", 200000);
			if (!db)
				alert("Failed to open the database on disk.  This is probably because the version was bad or there is not enough space left in this domain's quota");
		} else
			alert("Couldn't open the database.  Please try with a WebKit nightly with this feature enabled");
	} catch(err) {
		db = null;
		alert("Couldn't open the database.  Please try with a WebKit nightly with this feature enabled");
	}
	
	function saveNewSlotLocally (copiedEventObject)
    {
        //this.timestamp = new Date().getTime();
        var events = $('#calendar').fullCalendar('clientEvents')
        db.transaction(function (tx) 
        {
            tx.executeSql("INSERT INTO slots (title,start,end,status) VALUES (?, ?, ?, ?)", [copiedEventObject.title,copiedEventObject.start,copiedEventObject.end,copiedEventObject.status],function(result) {sendDataToCarista(copiedEventObject)});
        }); 
    }
	
	function sendDataToCarista(copiedEventObject)
	{
		var objJSON = {
		   "title" : copiedEventObject.title,
		   "start" : copiedEventObject.start,
		   "end" : copiedEventObject.end,
		   "status" : copiedEventObject.status
		 };
		//alert("SEND TO CARISTA: " + encodeURIComponent(JSON.stringify(objJSON)));
		var strJSON = encodeURIComponent(JSON.stringify(objJSON));
	   /* new Ajax.Request("ReceiveJSON.jsp",
	    {
			method: "post",
			parameters: "strJSON=" + strJSON,
			onComplete: Respond
	    });*/
	}
	
	function Respond(REQ)
	{
	//document.getElementById("ResponseDiv").innerHTML=REQ.responseText;
	}
	
	function deleteSlotsTable()
	{
		db.transaction(function(tx) {
			tx.executeSql("DROP TABLE slots", [],function(tx, result){loaded()})});
	}
	
	function getExistingSlots()
	{
		db.transaction(function(tx) {
			tx.executeSql("SELECT * FROM slots", [], function(tx, result) {
				var events = $('#calendar').fullCalendar('clientEvents');
				var slotEvents = new Array();
				for (var i = 0; i < result.rows.length; ++i) {
					var row = result.rows.item(i);
					var slot = {
								title  : row['title'],
								start  : row['start'],
								end  : row['end'],
								className : 'eventClass',
								textColor:'#000',
								allDay : false,
								status : row['status'],
								backgroundColor: 'transparent'}
					if(slot['status']=='pending') slot['status']='confirmed';//For TESTING!!!!!!!!!!!!!!
					slotEvents.push(slot);
					
				}
				$('#calendar').fullCalendar( 'addEventSource', slotEvents )
	 		
			}, function(tx, error) {
				alert('Failed to retrieve slots from database - ' + error.message);
			});
   		});
	}
	
	
	
	
	function loaded()
	{
		alert(navigator.onLine)
		db.transaction(function(tx) {
			tx.executeSql("SELECT COUNT(*) FROM slots", [], function(result) {
			//alert('already there');
			getExistingSlots();	
			}, function(tx, error) {
				tx.executeSql("CREATE TABLE slots (id  INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, title TEXT, start TEXT, end TEXT, status TEXT)", [], function(result) { 
					//alert('table created');
					$('#calendar').fullCalendar( 'removeEvents' );
				});
			});
		});
	}
	
	if (db != null)
    //addEventListener('load', deleteSlotsTable, false);
	addEventListener('load', loaded, false);
	
	
	
	
	var selectedItem = null;
	var selectedEventObject = null;
	var selectedDiv = null;
	

	$(document).ready(function() {
		
	
		/* initialize the external events
		-----------------------------------------------------------------*/
	
		$('#external-events div.external-event').each(function() {
			
			var objID = $(this).attr('id');
			objID = objID.substr(1,1);
			// create an Event Object
			// it doesn't need to have a start or end
			var eventObject = {
				title: $.trim($(this).text()),
				//id: objID,
				//data: objID, // use the element's text as the event title
				backgroundColor: 'transparent',
				borderColor: 'transparent',
				textColor:'#000'
			};
			
			
			// store the Event Object in the DOM element so we can get to it later
			$(this).data('eventObject', eventObject);
			
			$(this).click(function() {
			  selectedItem = true;
			  selectedEventObject = $(this).data('eventObject');
			  selectedDiv = this;
			  //alert(selectedEventObject.title);
			  $(this).css('background-color', '#00ff00')
			});
			
		});
	
	
		/* initialize the calendar
		-----------------------------------------------------------------*/
		
		$('#calendar').fullCalendar({
			header: {
				left: 'prev,next today',
				center: 'title',
				right: 'month,agendaWeek,agendaDay'
			},
			
			//theme:true,
			editable: true,
			//droppable: true,  this allows things to be dropped onto the calendar !!!
			eventRender: function(event, element) {
				var start = event.start.toString();
				start = start.substr(16,8);
				var end = event.end.toString();
				end = end.substr(16,8);
				element.html("<p>"+start+"</p><p class='"+ event.status +"'><img src='images/face.jpeg' width='35' style='float:right' />"+event.title+"<br/>"+event.status+"</p><p>"+end+"</p>");
			},
			
			eventClick: function(calEvent, jsEvent, view) {
				$('#popup').css('display', 'block');
				$('#popup').html("<input value='save and close' type='button' name='close' id='close' onclick=\"document.getElementById('popup').style.display='none'\"/>");
				var htmlStr = "<h2>Edit "+calEvent.title+"</h2>";
				htmlStr += "<p>Start "+calEvent.start+"</p>";
				htmlStr += "<p>Status "+calEvent.status+"</p>";
				htmlStr += "<p>End "+calEvent.end+"</p>"+$('#popup').html();
				$('#popup').html(htmlStr);
				//alert('Event: ' + calEvent.title + ' Scheduled to commence: ' + calEvent.start + ' and finish: ' + calEvent.end );
				//$(this).css('background-color', '#00ff00').add('<img src='+draggableObjects[calEvent.data].imgSrc+'/>');
		
			},
			
			dayClick: function(date, allDay, jsEvent, view) {

				if(selectedItem)
				{
					//var allDay = confirm('All day slot?');
					var copiedEventObject = $.extend({}, selectedEventObject);
					
					// assign it the date that was reported
					var dateStartStr=date.toString().substr(0,16);
					var dateEndStr=date.toString().substr(24,date.toString().length-1);
					//var startTime = prompt('Start time:','09:00:00');
					//var endTime = prompt('End time:','17:00:00');
					var startTime = '09:00:00';
					var endTime = '17:00:00';
					copiedEventObject.start = dateStartStr+startTime+dateEndStr;
					copiedEventObject.end = dateStartStr+endTime+dateEndStr;
					copiedEventObject.allDay = false;
					copiedEventObject.className = 'eventClass';
					copiedEventObject.status = 'pending';
					// render the event on the calendar
					$('#calendar').fullCalendar('renderEvent', copiedEventObject, true);
					$(selectedDiv).css('background-color', '#3366CC');
					
					saveNewSlotLocally(copiedEventObject);
					//alert("Copying "+copiedEventObject.title+ " to calendar on " + copiedEventObject.start +". The event is clickable once placed on the calendar");
					//events.push(copiedEventObject);
					//alert($('#calendar').fullCalendar);
					selectedItem = null;
					selectedEventObject = null;
					selectedDiv = null
				}
		
		
			},
			
			
			
		});
		
		
	});

</script>
<style type='text/css'>

	body {
		margin-top: 40px;
		text-align: center;
		font-size: 14px;
		font-family: "Lucida Grande",Helvetica,Arial,Verdana,sans-serif;
		}
		
	#wrap {
		width: 1100px;
		margin: 0 auto;
		}
		
	#external-events {
		float: left;
		width: 150px;
		padding: 0 10px;
		border: 1px solid #ccc;
		background: #eee;
		text-align: left;
		}
		
	#external-events h4 {
		font-size: 16px;
		margin-top: 0;
		padding-top: 1em;
		}
		
	.external-event { /* try to mimick the look of a real event */
		margin: 10px 0;
		padding: 2px 4px;
		background: #3366CC;
		color: #000;
		font-size: .85em;
		cursor: pointer;
		/*height:75px;
		background-image:url(images/face.jpeg);*/
		}
		
	#external-events p {
		margin: 1.5em 0;
		font-size: 11px;
		color: #666;
		}
		
	#external-events p input {
		margin: 0;
		vertical-align: middle;
		}

	#calendar {
		float: right;
		width: 900px;
		}
		
	.eventClass{
		/*background-image:url(images/face.jpeg);*/
		height:115px;
	}
	
	.pending{
		color:#0C3;	
	}
	
	.confirmed{
		color:#00F;	
	}
	
	
	#popup{
		position:absolute;
		width:400px;
		height:400px;
		background-color:#9C9;
		z-index:1000;
		display:none;
		text-align:left;
		padding:10px;	
	}

</style>
</head>
<body>

<div id='wrap'>

<div id='external-events'>
<h4>Click on a worker to select. Then click on a date to place a slot on the calendar associated with the worker.</h4>
<div class='external-event' id="s0">Elaine Smith</div>
<div class='external-event' id="s1">Freddy Smedley</div>
<div class='external-event' id="s2">Ron Atkinson</div>
<div class='external-event' id="s3">Kenneth Dalglish</div>
<div class='external-event' id="s4">Fabio Capello</div>
<input value='clear database' type='button' name='delete' id='delete' onclick="deleteSlotsTable()"/>
</div>

<div id='calendar'></div>
<div id="popup">
	<input value='save and close' type='button' name='close' id='close' onclick="document.getElementById('popup').style.display='none'"/>


</div>
<div style='clear:both'></div>
</div>

</body>
</html>
